import { Model, ObjectId, Document } from 'mongoose'
import mongoose from './mongoose'
import { cryptoString } from '../util/cryptoUtil'

const Types = mongoose.Schema.Types

export class AccountModel {
  id?: ObjectId
  accountName: string
  username?: string
  password?: string
  homepage?: string
  comment?: string
  createTime?: Date
  hash: string
  version?: string
}

export function computeAccountHash (account: AccountModel): string {
  const accStr =
  `${account.accountName || ''}${account.username || ''}${account.password || ''}${account.homepage || ''}${account.comment || ''}`
  return cryptoString(accStr)
}

const account = new mongoose.Schema({
  id: Types.ObjectId,
  accountName: { // 根据此字段判定是否是同一个记录，因此此字段唯一
    type: Types.String,
    required: true,
    index: 1
  },
  username: {
    type: Types.String,
    index: 1
  },
  password: {
    type: Types.String
  },
  homepage: {
    type: Types.String
  },
  comment: {
    type: Types.String
  },
  createTime: {
    type: Types.Date,
    default: Date.now,
    index: 1
  },
  hash: { // hash 由用户可控数据内容计算而来，用以判定数据是否发生改动
    type: Types.String,
    required: true,
    unique: true,
    index: 1
  },
  version: { // version 默认是最新版，当数据发生改动时，则新建一条记录，旧版记录版本号改为相应版本号，新版记录版本号仍为最新
    type: Types.String,
    required: true,
    default: 'lt', // latest
    index: 1
  }
}, {
  versionKey: false
})

const accountTableMap = new Map<string, Model<Document>>()

export default function getAccountModel (accountTableName: string): Model<Document> {
  if (accountTableMap.has(accountTableName)) {
    return accountTableMap.get(accountTableName)
  } else {
    accountTableMap.set(accountTableName, mongoose.model(accountTableName, account, accountTableName))
    return getAccountModel(accountTableName)
  }
}
